import React, { useEffect, useState } from 'react'
import style from './index.module.scss'
import { Radio } from 'antd'
import { getPrivacyApi, updatePrivacyApi } from '@/common/api'
import { connect } from 'react-redux'
const list = [
  { title: "点赞列表是否对外可见", key: 'favoriteShow',enable:true },
  { title: "收藏列表是否对外可见", key: 'collectionShow' ,enable:true},
  { title: "粉丝列表是否对外可见", key: 'fansShow' ,enable:true},
  { title: "关注列表是否对外可见", key: 'attentionShow',enable:true },
]
 function PrivacyList(props) {
  const { userId,privacy } = props
  const [privacyList,setList] = useState(list)
   useEffect(() => {
    getPrivacyFn()
   }, [])
   
   useEffect(() => {
     const privacyObj = {}
     privacyList.forEach(element => {
      privacyObj[element.key] = element.enable
     });
     if (Object.keys(privacyObj).length !== 0) {
      props.addPrivacy(privacyObj)
     }
   }, [privacyList])

   const getPrivacyFn = async () => {
    console.log(props.privacy,'@@@');
      setList(privacyList => {
      return  privacyList.map(item => ({
          ...item,
          enable: props.privacy[item.key] // 根据 key 在 obj 里查找对应的值
        }));
      })
    
  }
   const privacyChange = async (e,item) => {
     const { key } = item
     const RES = await updatePrivacyApi({ userId, key, enable: e.target.value })
     if (RES.code === 200) {
      setList(pre => {
        return pre.map(item => {
          if (item.key == key) {
            return { ...item, enable: e.target.value }
          }
          return item
         })
       })
     }
  }
  
  return (
    <div>
      {
        privacyList.map(item => (
          <div className={style.privacyList} key={item.key}>
            <div className='left'>
            {item.title}
            </div>
            <div className='right'>
              <Radio.Group onChange={(e) => privacyChange(e, item)} value={item.enable}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}> 否</Radio>
                </Radio.Group>
            </div>
          </div>
        ))
      }

    </div>
  )
}
export default connect((state => {
  return {
    privacy: state.privacy.privacyList
  }
}), dispatch => {
  return {
    addPrivacy: (val) => dispatch({ type: "all", payload: val })
  }
})(PrivacyList)